const BaseMonitor = require('./base-monitor');

class ServoMonitor extends BaseMonitor {
  constructor(deviceId, mqttConnector) {
    super(deviceId, mqttConnector);
    this.controlTopic = 'device/servo';
    this.stateTopic = 'device/servo/state';
    this.angle = '90'; // 初始角度
    this.unit = 'degree';
    this.status = 'normal';

    // 注册消息处理
    this.onMessage(this.stateTopic, this.handleStateMessage.bind(this));
  }

  // 初始化
  async init() {
    await this.subscribe(this.stateTopic);
    console.log('舵机监控模块已初始化');
  }

  // 处理状态消息
  handleStateMessage(message) {
    try {
      // 只处理JSON格式消息（已在mqtt-connector中解析）
      if (typeof message === 'object' && message.type === 'sensor-data' && message.data) {
        this.angle = message.data.value;
        this.unit = message.data.unit || 'degree';
        this.status = message.data.status || 'normal';

        console.log(`[舵机] 设备ID: ${message.deviceId}, 当前角度: ${this.angle}${this.unit === 'degree' ? '度' : this.unit}, 状态: ${this.status}`);

        // 触发状态更新事件（如果有监听器）
        if (this.onUpdate) {
          this.onUpdate({
            deviceId: message.deviceId,
            timestamp: message.timestamp,
            angle: this.angle,
            unit: this.unit,
            status: this.status
          });
        }
      } else {
        console.log(`无效的舵机状态消息格式: ${JSON.stringify(message)}`);
      }
    } catch (error) {
      console.error(`处理舵机状态消息错误: ${error.message}`);
    }
  }

  // 控制舵机角度
  async setAngle(angle) {
    try {
      // 确保角度在有效范围内
      if (angle < 0) angle = 0;
      if (angle > 180) angle = 180;

      const command = {
        deviceId: this.deviceId,
        timestamp: Date.now(),
        type: 'control-command',
        command: {
          action: 'set-angle',
          angle: Math.round(angle)
        }
      };

      await this.publish(this.controlTopic, JSON.stringify(command));
      console.log(`已发送舵机设置命令，角度: ${Math.round(angle)}度`);
      return true;
    } catch (error) {
      console.error(`发送舵机控制命令失败: ${error.message}`);
      return false;
    }
  }

  // 获取当前舵机状态
  getCurrentState() {
    return {
      angle: this.angle,
      unit: this.unit,
      status: this.status
    };
  }
}

module.exports = ServoMonitor;